package com.tduck.cloud.datav.service.charts;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.google.common.collect.Lists;
import com.tduck.cloud.datav.constant.ChartsConstants;
import com.tduck.cloud.datav.request.ChartDataRequest;
import com.tduck.cloud.datav.service.BaseChartDataService;
import com.tduck.cloud.datav.vo.EchartsSeriesVO;
import com.tduck.cloud.datav.vo.GroupQueryResult;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;


/**
 *  饼图
 */
@Component
public class BasicPieChartDataService extends BaseChartDataService {


    @Override
    public Map<String, Object> getChartData(ChartDataRequest request) {
        GroupQueryResult groupQueryResult = this.getGroupQueryDataList(request);
        Map<String, Object> result = MapUtil.of();
        List<String> groupDataList = groupQueryResult.getGroupDataList();
        result.put(ChartsConstants.CATEGORIES, groupQueryResult.getGroupDataList());
        Map<String, List<Object>> groupAggsMap = groupQueryResult.getGroupAggsMap();
        for (String key : groupAggsMap.keySet()) {
            List<Object> aggs = groupAggsMap.get(key);
            List<Object> seriesItemList = Lists.newArrayList();
            for (int i = 0; i < aggs.size(); i++) {
                EchartsSeriesVO.SeriesItem seriesItem = new EchartsSeriesVO.SeriesItem();
                seriesItem.setName(CollUtil.get(groupDataList, i));
                seriesItem.setValue(aggs.get(i));
                seriesItemList.add(seriesItem);
            }
            EchartsSeriesVO echartsSeriesVO = new EchartsSeriesVO(key, seriesItemList);
            request.getIndex().stream().filter(item -> key.startsWith(item.getId())).findFirst().ifPresent(item -> echartsSeriesVO.setName(item.getLabel()));
            result.put(ChartsConstants.SERIES, Lists.newArrayList(echartsSeriesVO));
        }
        return result;
    }
}
